package com.broad.commerce.code.services;

import cn.hutool.core.io.FileUtil;
import com.broad.commerce.code.common.CustomizeFileFilter;
import com.broad.commerce.common.utils.core.LogUtils;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * @author stephen
 * @version V1.0
 * @date 2022-04-22 18:45
 * @description: ProjectRootPath
 **/
@Configuration
public class ProjectRootDirService {
	public static final Map<String, String> PROJECT_DIR_MAP = Maps.newHashMap();
	@Value("${spring.application.root-dir:mall-server}")
	private String rootProject;

	@PostConstruct
	private void initMap() {
		String userDir = System.getProperty("user.dir");
		if (!userDir.endsWith(this.rootProject)) {
			userDir = FileUtil.getParent(userDir, 1);
			if (!userDir.endsWith(this.rootProject)) {
				userDir = FileUtil.getParent(userDir, 1);
			}
		}
		this.getFilePaths(userDir);
		LogUtils.info(this.getClass(), "Project Root Path : ", PROJECT_DIR_MAP);
	}

	private void getFilePaths(String filePath) {
		List<File> files = FileUtil.loopFiles(new File(filePath), 3, CustomizeFileFilter.INSTANCE);
		for (final File file : files) {
			File parent = file.getParentFile();
			if (parent.isDirectory()) {
				PROJECT_DIR_MAP.put(parent.getName(), parent.getAbsolutePath());
			}
		}
	}
}
